package com.freak.freakmusic.net.factory

import android.text.TextUtils
import com.google.gson.Gson
import com.google.gson.TypeAdapter
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Converter
import java.io.IOException
import java.util.*

/**
 * @author freak
 * @date 2019/03/12
 */
class CustomResponseBodyConverter<T> internal constructor(
    private val gson: Gson,
    private val adapter: TypeAdapter<T>
) : Converter<ResponseBody, T> {
    private var mObject: JSONObject? = null

    @Throws(IOException::class)
    override fun convert(value: ResponseBody): T {
        var json = value.string()
        try {
            mObject = JSONObject(json)
            if (mObject!!.optInt("code") != 200) {
                val map = HashMap<String, Any>(2)
                map["code"] = mObject!!.optString("code")
                map["msg"] = mObject!!.optString("msg")
                val map1 = HashMap<String, Any>(0)
                map["data"] = map1
                json = gson.toJson(map)
            } else {
                if (TextUtils.equals("null", mObject!!.optString("data"))) {
                    val map = HashMap<String, Any>(2)
                    map["code"] = mObject!!.optString("code")
                    map["msg"] = mObject!!.optString("msg")
                    val map1 = HashMap<String, Any>(0)
                    map["data"] = map1
                    json = gson.toJson(map)
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }

        return adapter.fromJson(json)
    }
}
